package com.idp.web.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.idp.system.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 接口日志过滤器
 * @author king
 */
@Component
@WebFilter(filterName = "LogFilter" , urlPatterns = "/*")
public class LogFilter implements Filter {

	@Autowired
	private SysLogService logService;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		Date startTime = new Date();

		RequestWrapper servletRequest = null;
		ResponseWrapper servletResponse = null;

		if(request instanceof HttpServletRequest) {
			servletRequest = new RequestWrapper((HttpServletRequest)request);
		}

		if(response instanceof HttpServletResponse) {
			servletResponse = new ResponseWrapper((HttpServletResponse)response);
		}

		chain.doFilter(servletRequest != null ? servletRequest : request, servletResponse != null ? servletResponse : response);

		if(servletRequest != null) {

			String url = servletRequest.getRequestURI();

			boolean isExclude = url.contains(".html") || url.contains(".css") || url.contains(".js") || url.contains("/log/findByPage");

			if(!isExclude) {

				JSONObject param = new JSONObject();

				String query = servletRequest.getQueryString();

				if(StrUtil.isNotEmpty(query)) {

					String jsonStr = "{\"" + query.replaceAll("=", "\":\"").replaceAll("&", "\",\"") + "\"}";

					if(JSONObject.isValidObject(jsonStr)) {
						param.put("query",  JSONObject.parseObject(jsonStr));
					} else {
						param.put("query",  query);
					}
				}

				if(servletRequest.getRequestBody() != null) {

					String body = StrUtil.str(servletRequest.getRequestBody(), "UTF-8");

					if(JSONObject.isValidObject(body)) {
						param.put("body", JSONObject.parseObject(body));
					} else {
						param.put("body", body);
					}
				}

				String responseData = "";

				if(servletResponse != null) {
					responseData = StrUtil.str(servletResponse.getContent(), "UTF-8");
				}

				logService.saveLog(url, param.toString(), responseData, startTime);
			}
		}

		if(servletResponse != null) {
			ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(servletResponse.getContent());
	        outputStream.flush();
	        outputStream.close();
		}

	}

}
